﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data.OracleClient;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XmlAppliction.Doman;
using DevExpress.XtraCharts;
using XmlAppliction.PublicClass;
using System.Threading;
using XMLToWordLib;
using DevExpress.XtraGrid;

namespace XmlAppliction.TJControl
{
    public partial class ChartsShow : DevExpress.XtraEditors.XtraUserControl
    {
        #region 共有属性
        string titleFormateStr = "统计分析方案"; 
        string fileRootPath = Application.StartupPath + "\\ChartsConfig"; 
        List<ChartSerieUser> chartSerieUsers = new List<ChartSerieUser>();

        string GroupColName = "名称";
        string xColName="日期";
        string yColName="结果";
        private DataTable viewDataTable=null;
        private int DoRowNum;//当前处理到的行数 用于滚动条
        DBLinkPool dbLinkPool = new DBLinkPool();//数据库连接集合


        protected Series seriesSelected = null;
        protected SeriesPoint pointSelected = null;
        protected object selectedAnotherObject = null;
        MarkerKindItemCollection itemCollection;
        protected virtual bool SeriesSelection { get { return true; } }
        #endregion
        #region 构造函数
        public ChartsShow(string GroupColName, string xColName, string yColName, DateTime stime, DateTime etime)
        {


            InitializeComponent();
            initBase();
            initConfigCombox();


            this.chartControl1.SeriesTemplate.View = new DevExpress.XtraCharts.LineSeriesView();
            //this.chartControl1.SeriesTemplate.View = new DevExpress.XtraCharts.Area3DSeriesView();
            this.chartControl1.RuntimeSelection = true;
            this.chartControl1.ObjectSelected += new HotTrackEventHandler(Chart_ObjectSelected);

            SDateEdit.DateTime = stime;
            EDateEdit.DateTime = etime;

            
        }
        #endregion
        #region 视图调整
        public void initBase()
        {
            this.chartControl1.Series.Clear();
            this.itemCollection = MarkerKindItemCollection.CreateCollection();
            MarkerKindItem[] items = new MarkerKindItem[this.itemCollection.Count];
            this.itemCollection.CopyTo(items);
            this.comboBoxEditMarkerKind.Properties.Items.AddRange(items);
            ///this.comboBoxEditLabelAngle.Properties.Items.AddRange(new string[] { "0", "45", "90", "135", "180", "225", "270", "315" });
            this.comboBoxEditMarkerSize.Properties.Items.AddRange(MarkerKindItemCollection.GetSizeArray());

            
            //绑定列表
            viewDataTable=NewDatatable();
            SetColSeries(GroupColName, xColName, yColName);

            
            //gridView1.BestFitColumns();//设置宽度自动调节能显示内容
            //汇总行统计方式
            gridView1.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.Hidden;
            GridGroupSummaryItem item = new GridGroupSummaryItem();
            item.FieldName = yColName;
            item.SummaryType = DevExpress.Data.SummaryItemType.Sum;
            item.DisplayFormat = "( 统计总数{0} )";
            gridView1.GroupSummary.Add(item);


        }

        DataTable NewDatatable()
        {
            //初始化表数据
            DataTable table  = new DataTable();
            table.Columns.Add(GroupColName, typeof(string));
            table.Columns.Add(xColName, typeof(string));
            table.Columns.Add(yColName, typeof(Int32));


            table.Columns.Add("统计用时", typeof(string));
            table.Columns.Add("起始日期", typeof(string));
            table.Columns.Add("结束日期", typeof(string));
            table.Columns.Add("查询语句", typeof(string));
            table.Columns.Add("数据库连接编号", typeof(string));

            return table;
        }

        protected virtual void Chart_ObjectSelected(object sender, HotTrackEventArgs e)
        {
            if (e.Object is Series)
            {
                e.Cancel = !SeriesSelection;
                if (SeriesSelection)
                {
                    this.seriesSelected = (Series)e.Object;
                    this.pointSelected = e.AdditionalObject as SeriesPoint;

                    ViewControlPanle.Text = string.Format("视图设置------{0}", this.seriesSelected.Name);
                }
            } 
            UpdateViewControls();
        }

        private void UpdateViewControls()
        {
            if (this.seriesSelected != null)
            {
                LineSeriesView view=(seriesSelected.View as LineSeriesView);
                if (view == null) return;
                checkEditShowMarkers.Checked = view.LineMarkerOptions.Visible;
                checkEditShowLabels.Checked = seriesSelected.Label.Visible;
                colorEditMarkerColor.Color =view.Color  ;
                foreach (object obj in comboBoxEditMarkerKind.Properties.Items)
                {
                    MarkerKindItem item = (MarkerKindItem)obj;
                    if (item.MarkerKind == view.LineMarkerOptions.Kind)
                    {
                        comboBoxEditMarkerKind.SelectedItem = obj;
                    }
                }

                foreach (object obj in comboBoxEditMarkerSize.Properties.Items)
                {
                    string item = (string)obj;
                    if ( Convert.ToInt32(item) ==  view.LineMarkerOptions.Size)
                    {
                        comboBoxEditMarkerSize.SelectedItem = obj;
                    }
                }
            }        
        }



        private void checkEditShowLabels_CheckedChanged(object sender, EventArgs e)
        {
            if (this.seriesSelected != null)
            {
                this.seriesSelected.Label.Visible = checkEditShowLabels.Checked;
            }
        }
        //隐藏和显示全部统计数
        private void checkLabelAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkedit = sender as CheckEdit;
            foreach (Series series in chartControl1.Series)
            {
                series.Label.Visible = checkedit.Checked;
            }
        }
        private void checkEditShowMarkers_CheckedChanged(object sender, EventArgs e)
        {
            if (this.seriesSelected != null)
            {
                (seriesSelected.View as LineSeriesView).LineMarkerOptions.Visible = checkEditShowMarkers.Checked;
            }

        }
        //隐藏和显示全部标签
        private void checkMarkAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkedit = sender as CheckEdit;
            foreach (Series series in chartControl1.Series)
            {
                (series.View as LineSeriesView).LineMarkerOptions.Visible = checkedit.Checked;
            } 
           
        }

        //显示隐藏单条绘制线
        private void checkShowLine_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkedit = sender as CheckEdit;
            if (this.seriesSelected != null)
            {
                foreach (Series series in chartControl1.Series)
                {
                    if (this.seriesSelected == series)
                    {
                        series.Visible = checkedit.Checked;
                        break;
                    }
                }
            }
        }
        //显示隐藏全部绘制线
        private void checkShowAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit checkedit = sender as CheckEdit;
            foreach (Series series in chartControl1.Series)
            {
                series.Visible = checkedit.Checked;
            }

        }

        private void comboBoxEditMarkerKind_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxEditMarkerKind.SelectedIndex == -1)
                return;
            if (this.seriesSelected != null)
            {
                LineSeriesView view = seriesSelected.View as LineSeriesView;
                MarkerKindItem item = (MarkerKindItem)this.comboBoxEditMarkerKind.SelectedItem;
                view.PointMarkerOptions.Kind = item.MarkerKind;
            }
        }

        private void comboBoxEditMarkerSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxEditMarkerSize.SelectedIndex == -1)
                return;
            if (this.seriesSelected != null)
            {
                LineSeriesView view = seriesSelected.View as LineSeriesView;
                if (view != null)
                    view.LineMarkerOptions.Size = Convert.ToInt32(this.comboBoxEditMarkerSize.Text);
            }
        }

        private void colorEditMarkerColor_EditValueChanged(object sender, EventArgs e)
        {
            if (this.seriesSelected != null)
            {
                LineSeriesView view = seriesSelected.View as LineSeriesView;
                if (view != null)
                    view.Color = colorEditMarkerColor.Color;
            }
        }

        #endregion
        #region 方案下拉框初始化
        /// <summary>
        /// 初始化分析方案下拉列表
        /// </summary>
        void initConfigCombox()
        {
            try
            {
                int index; 
                string fileType = "";
               
                this.xmlCombox.Properties.Items.Clear();
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(fileRootPath);
                if (!dir.Exists)
                {
                    dir.Create();
                    return;
                }
                foreach (System.IO.FileInfo fileinfo in dir.GetFiles())
                {
                    index = fileinfo.Name.IndexOf('.');
                    fileType = fileinfo.Extension.ToLower().Trim();
                    if (index < 0) continue;
                    if (fileType == ".xml")
                    {
                        this.xmlCombox.Properties.Items.Add(fileinfo.Name.Substring(0, index)); 
                    }
                }
                if (this.xmlCombox.Properties.Items.Count > 0) xmlCombox.SelectedIndex = 0;
            }
            catch
            {
                MessageBox.Show("请检查曲线分析配置图！","错误", MessageBoxButtons.OK,  MessageBoxIcon.Error);
            }

        }
        #endregion
        #region 设置线条颜色
        public void SetColSeries(string GroupColName,string xColName,string yColName) 
        {
            this.GroupColName = GroupColName;
            this.xColName = xColName;
            this.yColName = yColName;

            this.chartControl1.SeriesDataMember = GroupColName;
            this.chartControl1.SeriesTemplate.ArgumentDataMember = xColName;
            this.chartControl1.SeriesTemplate.ValueDataMembers.AddRange(new string[] { yColName });
            this.chartControl1.SeriesDataMember = GroupColName;
        }
        void SetSeriesColor()
        {
            string name;
            int indexNum = 0;
            foreach (DevExpress.XtraCharts.Series series in this.chartControl1.Series)
            {
                indexNum=series.Name.LastIndexOf('_');
                if (indexNum < 0) indexNum = series.Name.Length;
                name = series.Name.Substring(0, indexNum);

                var selectPeos = from serieUser in chartSerieUsers
                                 where serieUser.Name == name
                                 select serieUser;
                int selCount = selectPeos.Count<ChartSerieUser>();
                if (selCount > 0)
                {
                    series.View.Color = selectPeos.First<ChartSerieUser>().SerieColor;
                }
            }


        }
        #endregion
        #region 设置显示模式
        public void SetSeriesView(DevExpress.XtraCharts.SeriesViewBase view  )
        {  
            this.chartControl1.SeriesTemplate.View =   view;
        }
        #endregion
        #region 增加统计 线条
        public void AddSerie(string tjID)
        {
            ChartSerieUser chartSerieUser = new ChartSerieUser();
            chartSerieUser.TjId = tjID;
            initchartSerieUser(chartSerieUser);
            chartSerieUsers.Add(chartSerieUser);
            upDataView( );
        }


        void initchartSerieUser( ChartSerieUser chartSerieUser)
        {
            if (chartSerieUser == null) return;
            //如果无相关参数  就重新查询数据库获取参数
            if (chartSerieUser.DoSql == null || chartSerieUser.DoSql == "")
            {
                try
                {
                    DataRow row = DBMgr.DbHelperOra.Query("select  t.统计项编号, t.统计项名称,t.执行语句, t.连接参数编号,t.连接参数 from v_tj_tjx t where t.统计项编号='" + chartSerieUser.TjId + "'    ").Tables[0].Rows[0];
                    chartSerieUser.DoSql = row["执行语句"].ToString();
                    chartSerieUser.TjId = chartSerieUser.TjId;
                    chartSerieUser.DblinkID = row["连接参数编号"].ToString();
                    chartSerieUser.ConnectionString = row["连接参数"].ToString();
                    chartSerieUser.Name = row["统计项名称"].ToString().Trim();
                }
                catch (Exception ex)
                {
                    throw new Exception("统计项编号不存在");
                }
            }
        }
       
        #endregion
        #region 刷新按钮
        private void ResetEdit_Click(object sender, EventArgs e)
        {
            upDataView();
        }

         

        #endregion
        #region 窗体事件
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Filter = "xml文件|*.xml";
            DialogResult showDialog = saveFileDialog1.ShowDialog();
            if (showDialog == DialogResult.OK)
            {
                XMLHelper.writeXMLChartConfig(saveFileDialog1.FileName, titleFormateStr, chartSerieUsers);
            }
        }

        private void saveNowData_Click(object sender, EventArgs e)
        {
            string msgstr = "";
            if (viewDataTable != null)
            {
                saveFileDialog1.Filter = "xml文件(*.xml)|*.xml|Excel文件(*.xls)|*.xls"; 
                DialogResult showdialog = saveFileDialog1.ShowDialog();
                if (showdialog == DialogResult.OK)
                {
                    string fileType = saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf('.')+1);
                    if (fileType == "xml")
                    {
                        XMLHelper.writeXMLChartTable(saveFileDialog1.FileName, viewDataTable);
                        msgstr="成功保存为XML文件！";
                    }
                    else if (fileType == "xls" || fileType == "xlsx")
                    {
                        gridView1.ExportToXls(saveFileDialog1.FileName);
                        msgstr="成功保存为Excel文档！";
                    }
                    else
                    {
                        msgstr = "请输入正确的文件类型！";
                    }
                    //viewDataTable.TableName = "item";
                    //viewDataTable.WriteXml(saveFileDialog1.FileName);
                    MessageBox.Show(msgstr);
                }
            }
        }
        #endregion
        #region 绘制新方案
        private void drowNowFABtn_Click(object sender, EventArgs e)
        {
            if (xmlCombox.SelectedText == "请选择...")
            {
                MessageBox.Show("请选择方案！", "提示",   MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            ChartSerieUser chartSerieUser;
            Color color;
            string colorStr ;
            int sIndex;
            int eIndex;
            int R;
            int G;
            int B;
            try
            {
                DataSet ds = new DataSet();
                ds.ReadXml(string.Format("{0}\\{1}.xml", fileRootPath, xmlCombox.Text));
                if (ds.Tables.Count > 0)
                {
                    chartSerieUsers.Clear();
                    titleFormateStr = ds.Tables[0].TableName;
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        chartSerieUser = new ChartSerieUser();
                        chartSerieUser.TjId = row["统计项编号"].ToString();
                        chartSerieUser.Name = row["统计项名称"].ToString();
                        colorStr = row["颜色"].ToString(); 
                        sIndex = colorStr.IndexOf('(')+1;
                        eIndex = colorStr.IndexOf(',');
                        R = int.Parse(colorStr.Substring(sIndex, eIndex - sIndex));
                        sIndex = eIndex+1;
                        eIndex = colorStr.LastIndexOf(',');
                        G = int.Parse(colorStr.Substring(sIndex, eIndex - sIndex));
                        sIndex = eIndex+1;
                        eIndex = colorStr.LastIndexOf(')');
                        B = int.Parse(colorStr.Substring(sIndex, eIndex - sIndex));

                        color= System.Drawing.Color.FromArgb( R,G,B); 
                        chartSerieUser.SerieColor = color;
                        initchartSerieUser(chartSerieUser);
                        chartSerieUsers.Add(chartSerieUser);
                    }
 
                    upDataView();
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("未找到方案：" + xmlCombox.Text + ex.Message,  "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void UpdateChartTitle()
        {
            string tjDStr;
            if (radioDay.Checked)
            {
                tjDStr = "天";
            }
            else if (radioMouth.Checked)
            {
                tjDStr = "月";
            }
            else
            {
                tjDStr = "周";
            }

            this.chartControl1.Titles[0].Text = string.Format("{0}_按{1}统计", titleFormateStr, tjDStr);

        }

        #endregion  
        #region 当统计过程中的操作
        private void btsEnableTimer_Tick(object sender, EventArgs e)
        {
            
            
            //如果在统计过程中 则什么都不做
            if (!isHuizhi)//绘制完成
            {
                setBtnEnable(true);

                UpdateChartTitle();
                btsEnableTimer.Stop();
                chartControl1.DataSource = viewDataTable;
                gridControl1.DataSource = viewDataTable;
                UpdateChartTitle();
                SetSeriesColor();
                simpleButton1.Text = "导出数据";
            }
            else
            {
                simpleButton1.Text = string.Format("{0}/{1}", DoRowNum, progressBarControl1.Properties.Maximum);
                progressBarControl1.Position = DoRowNum;
            }

        }



        void setBtnEnable(bool flog)
        {
            try
            {
                if (!flog)
                {
                    this.ParentForm.Text += "( 统计中... )";
                    progressBarControl1.Visible = true;
                }
                else
                {
                    int indexNum = this.ParentForm.Text.IndexOf('(');
                    if (indexNum < 0) indexNum = this.ParentForm.Text.Length;
                    this.ParentForm.Text = this.ParentForm.Text.Substring(0, indexNum);
                    //重置进度条
                    progressBarControl1.Visible = false;
                    progressBarControl1.Position = 0;
                }
                this.groupControl1.Enabled = flog;
                this.groupControl2.Enabled = flog;
                //this.ViewControlPanle.Enabled = flog;
                simpleButton1.Enabled = flog;
                this.ParentForm.ControlBox = flog;//关闭按钮

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion


        void ResetTable(List<ChartSerieUser> chartSerieUsers)
        {
            viewDataTable = NewDatatable();
            //初始化日期
            DateTime etime = SDateEdit.DateTime;
            DateTime stime = SDateEdit.DateTime;
            bool addYear = !(etime.Year == stime.Year);
            bool firstDate = false;

            //加入行头
            foreach (ChartSerieUser serieUser in chartSerieUsers)
            {
                //加入数据
                dbLinkPool.Add(serieUser.DblinkID, serieUser.DblinkID, serieUser.ConnectionString);
                firstDate = true;
                if (serieUser == null) continue;
                stime = SDateEdit.DateTime;  
                while (stime <= EDateEdit.DateTime)
                {
                    
                    if (radioDay.Checked)
                    {
                        etime = stime.AddDays(1);
                    }
                    else if (radioMouth.Checked)
                    {
                        etime = stime.AddMonths(1);
                    }
                    else
                    {
                        etime = stime.AddDays(7);
                    }
                    //加入日期值
                    DataRow newrow = viewDataTable.NewRow();
                    newrow[GroupColName] = serieUser.Name + "_" + serieUser.TjId; 
                    newrow[yColName] = 0;
                    if (addYear || firstDate)
                    {
                        firstDate = false;
                        newrow[xColName] = stime.ToShortDateString();
                    }
                    else
                    {
                        newrow[xColName] = string.Format("{0}-{1}", stime.Month, stime.Day);
                    } 
                    newrow["起始日期"] = stime.ToShortDateString();
                    newrow["结束日期"] = etime.ToShortDateString();
                    newrow["查询语句"] =   string.Format(serieUser.DoSql, stime.ToString(), etime.ToString());
                    newrow["数据库连接编号"] = serieUser.DblinkID;
                    //最后
                    stime = etime;
                    viewDataTable.Rows.Add(newrow);
                }
                
            }
        
        }
  
        bool isHuizhi = false;
        void upDataView()
        {
            //如果已经多线程统计数据则不操作
            if (isHuizhi) return;
            ResetTable(chartSerieUsers);

            //滚动条设置
            DoRowNum = 0;
            progressBarControl1.Properties.Maximum = viewDataTable.Rows.Count;

            #region 多线程统计
            isHuizhi = true;
            setBtnEnable(false);
            btsEnableTimer.Enabled = true;
            Thread thread = new Thread(new ThreadStart(TJTable));
            thread.IsBackground = true;
            thread.Start();
            #endregion
        }


        void TJTable()
        {
            if (viewDataTable == null) return; 
            string linkIdStr;
            string sql;
            DBLinkUser dbLinkUser;
            
            DateTime bgtjtime;
            DateTime endtjtime;
            try
            {
                //编列表统计数据
                //foreach (DataRow row in viewDataTable.Rows)
                for (int i = 0; i < viewDataTable.Rows.Count;i++ )
                {
                    if (viewDataTable.Rows[i] == null) continue;
                    bgtjtime=DateTime .Now;
                    linkIdStr = viewDataTable.Rows[i]["数据库连接编号"].ToString(); 
                    dbLinkUser = dbLinkPool.GetLinkUser(linkIdStr);
                    //连接数据库
                    dbLinkUser.Start();
                    sql = viewDataTable.Rows[i]["查询语句"].ToString();
                    viewDataTable.Rows[i][this.yColName] = dbLinkUser.GetTJNum(sql);
                    endtjtime=DateTime .Now;
                    viewDataTable.Rows[i]["统计用时"] = (endtjtime - bgtjtime).TotalSeconds.ToString();
                    DoRowNum++;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                isHuizhi = false;
            
            }
        }

       
        
      

        
        
    }
}
